package com.lzh.controller;

import com.lzh.common.bean.ResultBean;
import com.lzh.common.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.DispatcherServlet;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
public class UploadController extends BaseController {

    final String ROOT = "/attach";

    @Autowired
    HttpServletRequest request;

    Set<String> types;

    @PostConstruct
    public void init() {
        types = new HashSet<>();
        types.add("image/jpeg");
        types.add("image/png");
    }


    @PostMapping("/upload/batch")
    public ResultBean batchUpload(List<MultipartFile> files) {
        if (null == files || files.size() == 0)
            return new ResultBean(0, "请选择上传的文件", null);
        final Map map = new HashMap();
        //遍历 一个个上传
        files.forEach(el -> {
            ResultBean rs = upload(el);
            map.put(el.getOriginalFilename(), rs);
        });

        return success("上传结果", map);
    }


    @PostMapping("/upload")
    public ResultBean upload(MultipartFile file) {

        //限制文件类型
        // 获取文件类型
        /*String type = file.getContentType();

        if (!types.contains(type))
            return new ResultBean(0, "请上传jpg、png格式", null);*/

        //获取新的文件名
        String name = getNewFileName(file.getOriginalFilename());
        //获取服务器根目录
        DistDir dir = getDistDir();
        //上传文件 File
        try {
            file.transferTo(new File(dir.getRoot() + dir.getRelativePath(), name));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        DispatcherServlet dispatcherServlet;
        return success("上传成功", dir.getRelativePath() + "/" + name);
    }

    /**
     * 获取新的文件名
     *
     * @param fileName
     * @return
     */
    String getNewFileName(String fileName) {
        //获取文件的后缀
        int pos = fileName.lastIndexOf(".");
        String ext = fileName.substring(pos);//.jpg
        String newFileName = System.currentTimeMillis() + ext;
        return newFileName;
    }


    /**
     * 获取上传的附件存储目录
     *
     * @return
     */
    DistDir getDistDir() {
        //获取服务器根目录
        String root = request.getServletContext().getRealPath("/");
        //获取当前系统时间
        String date = getSysYMD();
        File file = new File(root + ROOT + "/" + date);
        if (!file.exists())
            file.mkdirs();//创建目录
        return new DistDir(root, ROOT + "/" + date);
    }

    class DistDir {
        String root;
        String relativePath;

        public DistDir(String root, String relativePath) {
            this.root = root;
            this.relativePath = relativePath;
        }

        public String getRoot() {
            return root;
        }

        public void setRoot(String root) {
            this.root = root;
        }

        public String getRelativePath() {
            return relativePath;
        }

        public void setRelativePath(String relativePath) {
            this.relativePath = relativePath;
        }
    }

    /**
     * 获取系统日期 20250208
     *
     * @return
     */
    String getSysYMD() {
        LocalDate now = LocalDate.now();
        return now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    }


}
